package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.IUserSerivce;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户接口管理")
@RestController
@RequestMapping("/users")
@Slf4j
@RequiredArgsConstructor    //只会对初始化的属性生构造函数
public class UserController {

    private final IUserSerivce userSerivce;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO) {
//        拷贝属性（使用hutu包3中的方法进行属性拷贝）
        User user = BeanUtil.copyProperties(userDTO, User.class);
//      新增用户
        userSerivce.save(user);
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("{id}")
    public void deleteUserById(@ApiParam("用户id") @PathVariable Long id) {
//      根据id删除用户
        userSerivce.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("/{id}")
    public UserVO queryUserById(@ApiParam("用户id") @PathVariable Long id) {
        return userSerivce.queryUserAndAddressById(id);
    }

    @ApiOperation("根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> queryUserByIds(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids) {
//        返回数据
        return userSerivce.queryUserAndAddressByIds(ids);
    }


    @ApiOperation("扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deductMoneyById(@ApiParam("用户id") @PathVariable("id") Long id, @ApiParam("扣减的金额") @PathVariable("money") Integer money) {
        userSerivce.deductBalance(id, money);
    }


    @ApiOperation("根据复杂条件查询用户接口")
    @GetMapping("/list")
    public List<User> queryUsers(UserQuery query){
//        查询用户
        return userSerivce.queryUsers(query.getName(),query.getStatus(),query.getMinBalance(),query.getMaxBalance());
    }


    @ApiOperation("根据条件分页查询用户接口")
    @GetMapping("/page")
    public PageDTO<UserVO> queyUserPage(UserQuery query){
        return userSerivce.queryUsersPage(query);
    }
}
